package com.atom.app.lifecycle.base

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.view.KeyEvent
import androidx.appcompat.view.ContextThemeWrapper
import androidx.databinding.ViewDataBinding
import com.atom.app.lifecycle.R
import com.atom.app.lifecycle.utils.LanguageUtil
import com.atom.module.mvvm.base.view.activity.AbstractBaseMVVMActivity

abstract class AppActivity<V : ViewDataBinding, VM : AppViewModel<*>> :
    AbstractBaseMVVMActivity<V, VM>() {


    override fun attachBaseContext(newBase: Context?) {
        newBase ?: let {
            super.attachBaseContext(newBase)
            return
        }
        // 多语言适配
        val language = LanguageUtil.getLanguage()
        val context = LanguageUtil.attachBaseContext(newBase, language);
        val configuration = context.resources.configuration;
        val wrappedContext = object : ContextThemeWrapper(context, R.style.Theme_Testmvvm) {
            override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
                overrideConfiguration?.setTo(configuration)
                super.applyOverrideConfiguration(overrideConfiguration)
            }
        };
        super.attachBaseContext(wrappedContext);
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 更新Application中的local
        LanguageUtil.updateApplicationLocale(
            AppApplication.getInstance(),
            LanguageUtil.getLanguage()
        )
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        viewModel.onKeyDown(keyCode, event)
        return super.onKeyDown(keyCode, event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        viewModel.onActivityResult(requestCode, resultCode, data)
    }
}